package com.ksyun.ks3.services.request;

import android.content.Context;
import android.util.Log;

import com.ksyun.ks3.services.handler.AsyncHttpResponseHandler;
import com.ksyun.ks3.util.OkhttpInternalUtils;
import com.ksyun.ks3.util.StringUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import okio.Buffer;
import okio.BufferedSink;
import okio.ForwardingSink;
import okio.Okio;
import okio.Sink;
import okio.Source;

public class ProgressRequestBody extends RequestBody {

    private AsyncHttpResponseHandler handler;
    private static final int SEGMENT_SIZE = 2048; // okio.Segment.SIZE

    private InputStream inputStream;
    private String contentType;
    private long contentLength;

    public ProgressRequestBody(InputStream input, long contentLength, String contentType,
                                        AsyncHttpResponseHandler handler) {
        this.inputStream = input;
        this.contentType = contentType;
        this.contentLength = contentLength;
        this.handler =handler;
    }

    @Override
    public MediaType contentType() {
        return MediaType.parse(this.contentType);
    }

    @Override
    public long contentLength() throws IOException {
        return this.contentLength;
    }

    @Override
    public void writeTo(BufferedSink sink) throws IOException {
        if (sink instanceof Buffer
                || sink.toString().contains(
                "com.android.tools.profiler.support.network.HttpTracker$OutputStreamTracker")) {
            return;
        } else {
            Source source = Okio.source(this.inputStream);
            long total = 0;
            long read, toRead, remain;
            while (total < contentLength) {
                remain = contentLength - total;
                toRead = Math.min(remain, SEGMENT_SIZE);

                read = source.read(sink.buffer(), toRead);
                if (read == -1) {
                    break;
                }

                total += read;
                sink.flush();

                if (handler != null && total != 0) {
                    handler.onProgress(total, contentLength);
                }
            }
            if (source != null) {
                source.close();
            }
        }
    }

}
